package com.jiepos.mpos.core.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppMenuAuthInfDao;
import com.jiepos.mpos.common.dao.MenuButtonDao;
import com.jiepos.mpos.core.util.ContextUtils;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 
 * <p>标题: —— 显示某个菜单的操作权限，用户列表页面控制</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @author 娄伟峰
 * @version 1.0
 * @since 2017年4月18日 下午7:40:41
 * @history（历次修订内容、修订人、修订时间等）
 */
public class ButtonOperateTag extends BodyTagSupport {

	private static final long serialVersionUID = 7366326665143937358L;

	private final Logger log = LoggerFactory.getLogger(ButtonOperateTag.class);

	/**
	 * 菜单编码
	 */
	private String menuCode;

	

	/**
	 * 页面按钮类型，1：列表页，2：详细页
	 */
	private String buttonType;
	/**
	 * 工具栏名称
	 */
	private String toolBarName;
	/**
	 * 查询是否需要
	 */
	private String isInquery;
	@Override
	public int doEndTag() {
		if (StringUtils.isBlank(buttonType)) {
			buttonType = "1";
		}
		WebApplicationContext wac = WebApplicationContextUtils
				.getWebApplicationContext(pageContext.getServletContext());
		AppMenuAuthInfDao menuAuthDao = (AppMenuAuthInfDao) wac.getBean("appMenuAuthInfDao"); 
		MenuButtonDao menuButtonDao = (MenuButtonDao) wac.getBean("menuButtonDao");

		HttpSession session = pageContext.getSession();
		// 获取当前登陆用户的角色id
		String roleId = String.valueOf(session.getAttribute(SystemConstant.SESSION_ROLE_UUID));
		// 根据当前登陆用户的角色id和当前菜单id查询此角色的权限。
		String sql = "select * from " + Table.T_APP_MENUAUTH_INF + " where role_uuid=? ";
		sql = sql + " and menu_uuid=? ";
		sql = sql + " and " + SystemConstant.REC_ST + "!=? ";
 
		List paramList = new ArrayList();
		paramList.add(roleId);
		paramList.add(menuCode);
		paramList.add(SystemConstant.DEL_STATUS);
		List<Map> menuAuthList =  menuAuthDao.queryForList(sql,paramList);
		String returnContent = "";//"<div style=\"padding:3px\" class=\"datagrid-toolbar\">";
		if (menuAuthList != null && menuAuthList.size() > 0) {
			Map menuAuthMap = menuAuthList.get(0);
			String auth_buttons = String.valueOf(menuAuthMap.get("AUTH_BUTTONS"));
			//log.debug("auth_buttons==" + auth_buttons);
			if (!StringUtils.isBlank(auth_buttons)) {
				// 如果当前角色的当前操作不为空，则根据buttonIds查询出这些菜单所有的操作
				String[] sqlAuthButtonIds = auth_buttons.split(",");
			//	log.debug("sqlAuthButtonIds==" + sqlAuthButtonIds);
				StringBuffer buffer = new StringBuffer();  
				for(int i = 0 ; i < sqlAuthButtonIds.length ; i++){
					 buffer.append("?, ");  
				}
				 buffer.deleteCharAt(buffer.length() - 1);  
				 buffer.deleteCharAt(buffer.length() - 1);  
				String menuButtonSql = "select *  from " + Table.T_APP_MENUBUTTON_INF;
				menuButtonSql = menuButtonSql + " where button_uuid in ("+buffer.toString()+") and  "
						+ SystemConstant.REC_ST + "!=? " ;
				menuButtonSql = menuButtonSql + " and button_type=?";
				menuButtonSql = menuButtonSql + " order by button_orders";
				Map menuButtonMap = null;
				List paramList2 = new ArrayList();
				for(int i = 0 ; i < sqlAuthButtonIds.length ; i++){
					paramList2.add(sqlAuthButtonIds[i]);
				}
				paramList2.add(SystemConstant.DEL_STATUS);
				paramList2.add(buttonType);
				List<Map> menuButtonList = menuButtonDao.queryForList(menuButtonSql,paramList2);

				for (int i = 0; i < menuButtonList.size(); i++) {
					menuButtonMap = menuButtonList.get(i);
					String buttonCode = StringUtils.objToString(menuButtonMap.get("BUTTON_CODE"));
					String buttonName = StringUtils.objToString(menuButtonMap.get("BUTTON_NAME"));
					String buttonUrl = StringUtils.objToString(menuButtonMap.get("BUTTON_URL"));
					String functionName = StringUtils.objToString(menuButtonMap.get("FUNCTION_NAME"));
					String buttonIconcls = StringUtils.objToString(menuButtonMap.get("BUTTON_ICONCLS"));
					if (!StringUtils.isBlank(returnContent)) {
						returnContent = returnContent + " ";
					}
					String newFunctionName = "";
					if (!StringUtils.isBlank(functionName)) {
						String appName = ContextUtils.getAppName();
						
						if(!StringUtils.isBlank(appName)){
							appName = "/" + ContextUtils.getAppName() ;
						}
					//	log.debug("appName="+appName);
						newFunctionName = functionName + "('"+ appName+buttonUrl + "')";
					}
					
					returnContent = returnContent + "<a href=\"#\"   id='" + buttonCode
							+ "'  class=\"easyui-linkbutton\" plain=\"true\" iconCls=\""+buttonIconcls+"\"     onclick=\""
							+ newFunctionName + "\">"+buttonName+"</a>" ;
					
					returnContent = returnContent + "<span class=\"datagrid-btn-separator\" style=\"vertical-align: middle;display:inline-block;float:none\"></span>";
				}
			}
		}
		if(buttonType.equals("0")){
			if(StringUtils.isBlank(isInquery)){
			//	returnContent = returnContent + " <input type=\"submit\" class=\"btn btn-primary\" style=\"float:right\" value=\"查询\" />";
			}
		}
		JspWriter writter = pageContext.getOut();
	//	log.debug("Generated code by Button tag : " + returnContent);
		try {
		//	writter.print(returnContent + " </div> ");
			writter.print(returnContent );
		} catch (IOException e) {
			log.error("buttonOperate: build error.");
		}
		return EVAL_PAGE;
	}

	public String getMenuCode() {
		return menuCode;
	}

	public void setMenuCode(String menuCode) {
		this.menuCode = menuCode;
	}

	public String getButtonType() {
		return buttonType;
	}

	public void setButtonType(String buttonType) {
		this.buttonType = buttonType;
	}

	public String getToolBarName() {
		return toolBarName;
	}

	public void setToolBarName(String toolBarName) {
		this.toolBarName = toolBarName;
	}
	/**
	 * @return the isInquery
	 */
	public String getIsInquery() {
		return isInquery;
	}

	/**
	 * @param isInquery the isInquery to set
	 */
	public void setIsInquery(String isInquery) {
		this.isInquery = isInquery;
	}

	/**
	 * @return the log
	 */
	public Logger getLog() {
		return log;
	}

}
